<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>

        /*全局样式 */
        html, body, #app {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        /* 卡片区域 */
        .el-card {
            box-shadow: 0 1px 1px rgba(0, 8, 10, 0.15);
        }

        /* 表格样式 */
        .el-table {
            margin-top: 15px;
            font-size: 12px;
            min-width: 350px;
        }

        /*布局充满：container下的每个块充满*/
        .home-container {
            height: 100%;
        }

        /*头样式*/
        .el-header {
            background-color: #373d41;
            display: flex;
            justify-content: space-between;
            /*左右分布 padding-left: 0;*/
            /*logo图片距左为0 align-items: center;*/
            /*水平居中 color: #fff;*/
            /*文字颜色 font-size: 20 px;*/
        }

        .lt_info {
            /*左侧div(logo和文字) 加布局 display: flex;*/
            display: flex;
            align-items: center;
        }

        .lt_info span {
            color: aqua;
            margin-left: 10px;
            font-size: 20px;
        }

        .user_info {
            /*小手*/
            cursor: pointer;
            display: flex;
            padding: 0 10px;

        }

        .user_desc {
            /*伸缩盒子*/
            display: flex;
            /*justify-content: center;*/
            /*垂直居中*/
            align-items: center;
        }

        /*左上角logo*/
        .logo_img {
            width: 55px;
            height: 55px;
            margin: 0 30px;
        }

        /*底部*/
        .el-footer {
            background-color: #373d41;
            color: aqua;
            text-align: center;
            line-height: 60px;
        }

        .el-main {
            /*background: url("./images/bg.jpg");*/
            background-color: #E9EEF3;
            color: #333;
            text-align: center;
            /*line-height: 160px;*/
        }

        /*v-cloak:解决数据加载时页面闪烁问题*/
        [v-cloak] {
            display: none;
        }

    </style>
</head>
<body>
<div id="app" v-cloak>

    <el-container class="home-container">
        <el-header>
            <div class="lt_info">
                <img src="./img/logo.jpg" alt="编程之外" class="logo_img"/>
                <span>编程之外の员工管理系统</span>
            </div>

            <div class="user_info">
                <el-dropdown class="user_desc">
                    <div style="padding: 20px">
                        <img src="./img/toux.jpg" title="user" style="width: 30px;border-radius: 50%;" alt=""/>
                    </div>
                    <!--<div style="">-->
                    <!--    <span style="font-size: 16px;color: aqua;padding: 5px">-->
                    <!--        username-->
                    <!--    </span>-->
                    <!--</div>-->
                    <!--下拉菜单 margin-right: 50px;-->
                    <div>
                        <el-dropdown-menu slot="dropdown" style="box-shadow: 0 0 10px 5px rgba(54,45,255,0.9);">
                            <el-dropdown-item>{{user.username}}</el-dropdown-item>
                            <el-dropdown-item @click.native="logout">安全退出</el-dropdown-item>
                        </el-dropdown-menu>
                    </div>
                </el-dropdown>
            </div>
        </el-header>

        <el-main>
            <div>
                <!-- 卡片视图区 -->
                <el-card>
                    <el-row :gutter="25">
                        <el-col :span="10">
                            <!-- name 搜索(模糊查询) -->
                            <el-input placeholder="请输入要查询的员工姓名" v-model="findAllEmpParam.name" clearable
                                      @clear="getEmpList">
                                <el-button slot="append" icon="el-icon-search" @click="getEmpList"></el-button>
                            </el-input>
                        </el-col>
                        <!--添加-->
                        <el-col :span="4">
                            <el-button type="primary" @click="addDialogVisible = true">添加员工</el-button>
                        </el-col>
                    </el-row>
                    <!-- 用户列表 -->
                    <el-table :data="empList" border stripe>
                        <el-table-column label="ID" prop="id"></el-table-column>
                        <el-table-column label="员工姓名" prop="name"></el-table-column>

                        <el-table-column label="头像" prop="photopath">
                            <template slot-scope="scope">
                                <!--<img :src="scope.row.photopath" style="width: 50%;" title="员工头像">-->
                                <img :src="'http://localhost:8081/ems_vue/'+scope.row.photopath" style="width: 50%;" title="员工头像">
                            </template>
                        </el-table-column>
                        <!--<el-table-column label="头像" prop="photopath"></el-table-column>-->

                        <el-table-column label="工资/元" prop="salary"></el-table-column>
                        <el-table-column label="年龄" prop="age"></el-table-column>

                        <el-table-column label="操作" class="right_operation">
                            <template slot-scope="scope">
                                <!-- 修改 -->
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                           @click="showEditDialog(scope.row.id)"></el-button>
                                <!-- 删除 -->
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                           @click="deleteEmpInfo(scope.row.id)"></el-button>
                                <!-- 权限 -->
                                <el-tooltip effect="dark" content="其他信息" placement="top-start" :enterable="false">
                                    <!--<el-button type="warning" icon="el-icon-setting" size="mini"></el-button>-->
                                    <el-button type="success" @click="toPlace(scope.row.id)" icon="el-icon-picture"
                                               circle></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页：:current-page 当前页码 -->
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="findAllEmpParam.page"
                            :page-sizes="[1, 3, 5, 100]"
                            :page-size="findAllEmpParam.pageSize"
                            background
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="totals"
                    ></el-pagination>
                </el-card>
                <!-- 卡片视图区结束 -->

                <!--添加员工对话框-->
                <el-dialog title="添加员工" :visible.sync="addDialogVisible" @close="addDialogClosed" width="50%">
                    <!-- 内容主体区域 -->
                    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                        <!-- 姓名 -->
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="addForm.name"></el-input>
                        </el-form-item>
                        <!-- 头像 -->
                        <el-form-item label="头像" prop="photopath">
                            <!--<el-input v-model="addForm.photopath"></el-input>-->
                            <input type="file" ref="myfile" name="photo"/>
                            <!--<el-upload class="upload-demo" drag
                                        action="http://localhost:8081/ems_vue/addEmp"
                                        multiple
                                        ref="myfile"
                                        before-upload="onBeforeUploadImage"
                                        http-request="UploadImage">
                                 <i class="el-icon-upload"></i>
                                 <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                 <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                            </el-upload>-->

                        </el-form-item>
                        <!-- 工资 -->
                        <el-form-item label="工资" prop="salary">
                            <el-input v-model="addForm.salary"></el-input>
                        </el-form-item>
                        <!-- 年龄 -->
                        <el-form-item label="年龄" prop="age">
                            <el-input v-model="addForm.age"></el-input>
                        </el-form-item>
                    </el-form>
                    <!-- 内容底部区域 -->
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="addDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="addEmp">确 定</el-button>
                    </span>
                </el-dialog>
                <!--添加数据对话框结束-->

                <!-- 修改用户对话框 -->
                <el-dialog title="修改员工信息" :visible.sync="editDialogVisible" width="50%" @colse="editDialogClosed">
                    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
                        <!-- 员工姓名 -->
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="editForm.name"></el-input>
                        </el-form-item>
                        <!-- 头像 -->
                        <el-form-item label="头像" prop="photopath">
                            <el-input v-model="editForm.photopath"></el-input>
                        </el-form-item>
                        <!-- 工资 -->
                        <el-form-item label="工资" prop="salary">
                            <el-input v-model="editForm.salary"></el-input>
                        </el-form-item>
                        <!-- 年龄 -->
                        <el-form-item label="年龄" prop="age">
                            <el-input v-model="editForm.age"></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="editDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="editEmpInfo">确 定</el-button>
                    </span>
                </el-dialog>

            </div>
        </el-main>

        <el-footer style="text-align: left">清新简洁的员工管理系统</el-footer>

    </el-container>

</div>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

<script>
    const $http = axios.create({
        baseURL: 'http://localhost:8081/ems_vue',
        timeout: 7000,
        headers: {'X-Custom-Header': 'foobar'}
    });
    new Vue({
        el: '#app',
        data: {
            // 用来存放登录后的用户信息
            user: {},
            // 员工列表数据
            empList: [],
            // 请求员工数据参数（like，limit）
            findAllEmpParam: {
                name: "", // name 模糊查询，摸为空
                page: 1, // 当前页码，设置默认为1
                pageSize: 5 //页码大小，设置初始为5条数据
            },
            totals: 0, // 数据总条数
            // ============================添加员工信息==================
            addDialogVisible: false,// 添加数据对话框：false 隐藏 true 显示
            // 添加员工表单项 请求参数
            addForm: {},
            // 添加数据对话框验证规则
            addFormRules: {
                name: [
                    {required: true, message: "员工姓名不能为空", trigger: "blur"}
                ],
                salary: [
                    {required: true, message: "工资不能为空", trigger: "blur"},
                    {min: 0, max: 10, message: "长度在 1 ~ 10 个字符", trigger: "blur"}
                ],
                age: [
                    {required: true, message: "年龄不能为空", trigger: "blur"},
                    {min: 1, max: 3, message: "长度在 1 ~ 3 个字符", trigger: "blur"}
                ]
            },
            // =====================修改员工信息==============================
            // 控制修改对话框显示true/隐藏false
            editDialogVisible: false,
            // 修改员工信息
            editForm: {},
            // 修改员工表单验证规则
            editFormRules: {
                // name: [
                //     {required: true, message: "员工姓名不能为空", trigger: "blur"}
                // ],
                // salary: [
                //     {required: true, message: "工资不能为空", trigger: "blur"},
                //     {min: 0, max: 10, message: "长度在 1 ~ 10 个字符", trigger: "blur"}
                // ],
                // age: [
                //     {required: true, message: "年龄不能为空", trigger: "blur"},
                //     {min: 1, max: 3, message: "长度在 1 ~ 3 个字符", trigger: "blur"}
                // ]
            },

        },
        //created()： vue生命周期函数，页面创建时执行
        created() {
            this.getLoginUser();
            this.getEmpList();
        },
        methods: {
            // 获取登录后存入 localStorage 中的 user
            getLoginUser() {
                // 根据 k 拿到登录时存入 localStorage 的 user（json字符串）
                let userJSONString = localStorage.getItem("user");
                if (userJSONString != null) {
                    // 将json字符串转化为对象
                    let userDB = JSON.parse(userJSONString);
                    console.log("存入localStorage中的user对象：", userDB);
                    this.user = userDB;
                } else {
                    // this.$message("尚未登录，请先登录！！！");
                    alert("尚未登录，请先登录！！！");
                    location.href = './login.html';
                }
            },
            //安全退出方法
            logout() {
                // 清除localStorage中的用户数据，否则浏览器中还存在user信息
                localStorage.clear();
                //返回到登录页
                location.href = './login.html';
                // //方式二
                // localStorage.removeItem("user");
                // location.reload(true)
            },
            // 获得所有员工信息
            async getEmpList() {
                const {data: res} = await $http.get("/findAllEmp?name=" +
                    this.findAllEmpParam.name + "&page=" + this.findAllEmpParam.page + "&pageSize=" + this.findAllEmpParam.pageSize
                );
                console.log("后端返回的员工列表数据：", res);
                if (res != null) {
                    this.empList = res.empList;
                    this.totals = res.empCounts;
                    // this.$message.success("查询成功！");
                } else {
                    this.$message.error("员工信息获取失败！");
                }
            },
            // 监听pageSize页面大小改变的事件
            handleSizeChange(newSize) {
                this.findAllEmpParam.pageSize = newSize;
                console.log("每页多少条数据：", newSize);
                this.getEmpList(); // 页面大小发生改变重新请求数据
                this.$message.success("查询成功！");
            },
            // 监听page当前页改变的事件
            handleCurrentChange(newPage) {
                console.log("当前页码：", newPage);
                this.findAllEmpParam.page = newPage;
                this.getEmpList(); // page当前页发生改变重新申请数据
            },

            // ============================添加员工信息==================
            // 监听添加员工对话框（关闭）
            addDialogClosed() {
                this.$refs.addFormRef.resetFields();// 重置表单项
            },
            // 添加员工
            addEmp() {
                console.log("要添加的员工信息：", this.addForm);
                console.log("要上传的图片：", this.$refs.myfile.files);
                console.log("具体上传的图片详情：", this.$refs.myfile.files[0]);
                //文件上传时 请求方式必须是post ，enctype 必须为 multipart/form-data
                let formData = new FormData();  //模拟一个表单（用来给后端传递数据）
                formData.append("name", this.addForm.name);
                formData.append("salary", this.addForm.salary);
                formData.append("age", this.addForm.age);
                formData.append("photo", this.$refs.myfile.files[0]);
                axios({
                    method: "post",
                    // enctype: "multipart/form-data",
                    url: "http://localhost:8081/ems_vue/addEmp",
                    data: formData,
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(res => {
                    console.log("后端返回的数据", res.data);
                    if (res.data.state){
                        this.$message.success(res.data.msg);
                        // 隐藏对话框
                        this.addDialogVisible = false;
                        this.getEmpList(); // 数据发生改变重新请求数据
                    }else {
                        this.$message.error("添加失败！");
                    }
                })

                // axios.post("http://localhost:8081/add", this.addForm).then((res) => {
                //     if (res.data.state) {
                //         // alert(res.data.msg);//添加成功
                //         this.$message.success("添加成功！！！");
                //         //隐藏
                //         this.addDialogVisible = false;
                //         this.getEmpList();
                //     } else {
                //         // alert(res.data.msg);//添加失败
                //         this.$message.error("添加失败！！！");
                //     }
                // })

                // this.$refs.addFormRef.validate(async valid =>{
                //     console.log("验证规则是否通过：",valid);
                //     if( !valid ) return;  // 不符合验证规则
                //
                //     const {data:res} = await this.$http.post("/addEmp",this.addForm);
                //     if (res !== "success") {
                //         userinfo.state = !userinfo.state;
                //         return this.$message.error("操作失败！！！");
                //     }
                //     this.$message.success("操作成功！！！");
                //     //隐藏对话框
                //     this.addDialogVisible = false;
                //     this.getUserList();
                // })
            },
            // ===================添加员工数据结束=================

            //去到列表页面，并带上id
            toPlace(id) {
                location.href = './placelist.html?id=' + id
            },
            // ====删除按钮====
            async deleteEmpInfo(id) {
                // 弹框
                const confirmResult = await this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                // 成功删除为confirm 取消为 cancel
                if (confirmResult !== 'confirm') {
                    return this.$message.info("已取消删除");
                }
                const {data: res} = await $http.get("/deleteEmp?id=" + id);
                this.$message.success(res.msg);
                this.getEmpList();

                /*axios.get("http://localhost:8081/delete?id=" + id).then((res) => {
                    if (res.data.state) {
                        this.$message.success("删除成功！！！");
                        this.getEmpList();
                        // location.reload(true) //刷新当前页面
                    } else {
                        this.$message.error("删除失败！！！");
                    }
                });*/
            },
            // ====删除方法结束==========

            // =======根据id查询要修改的员工信息：点击修改，展示修改框
            // scope.row.id拿到要修改数据的id==========
            async showEditDialog(id) {

                // const {data: res} = await this.$http.get("getUpdate?id=" + id);
                const {data: res} = await $http.get("/findUpdate?id=" + id);

                this.editForm = res;  //查出要修改的数据并展示
                this.editDialogVisible = true;  //显示修改卡片
            },
            // 关闭修改窗口
            editDialogClosed() {
                this.$refs.editFormRef.resetFields();
            },
            // 修改员工信息
            editEmpInfo() {
                this.$refs.editFormRef.validate(async valid => {
                    console.log("========valid:=====：", valid);
                    if (!valid) return;
                    const {data: res} = await $http.post("/update", this.editForm);
                    console.log("后端返回的res：", res);
                    if (res > 0) {
                        this.$message.success("修改成功！！！");
                        //隐藏修改框
                        this.editDialogVisible = false;
                        this.getEmpList();
                    } else {
                        this.$message.error("修改失败！");
                    }

                });
            },
        }
    })
</script>
</html>
